﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace FuckCore.DAO
{
    /// <summary>
    /// Utility for DAO layer
    /// </summary>
    public static class Utils
    {
        /// <summary>
        /// Build container Expression for LINQ
        /// </summary>
        /// <typeparam name="TElement"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="valueSelector"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(
            Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
        {
            if (null == valueSelector)
            {
                throw new ArgumentNullException("valueSelector");
            }
            if (null == values)
            {
                throw new ArgumentNullException("values");
            }
            ParameterExpression parameter = valueSelector.Parameters.Single();
            if (!values.Any())
            {
                return e => false;
            }
            IEnumerable<Expression> equals =
                values.Select(
                    value =>
                    (Expression) Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof (TValue))));
            Expression body = equals.Aggregate(Expression.Or);
            return Expression.Lambda<Func<TElement, bool>>(body, parameter);
        }
    }
}